package mspbots.data.sync.timedoctorv2.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.sync.BaseReceiver;
import mspbots.data.sync.ResultMessageModel;
import mspbots.data.sync.timedoctorv2.model.TimeDoctorProjects;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.Iterator;
import java.util.Optional;

/**
 * @author Jay Yang
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class TimeDoctorProjectsReceiver extends BaseReceiver {

    @RabbitListener(queues = "timedoctor.projects.sync")
    public void processProjects(ResultMessageModel model) {
        log.debug("processProjects[timedoctor.projects.sync] ResultMessageModel {}", model);
        if (!ObjectUtils.isEmpty(model.getEntity()) && ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            Iterator<JsonNode> nodes = model.getEntity().elements();
            while (nodes.hasNext()) {
                JsonNode node = nodes.next();
                TimeDoctorProjects project = TimeDoctorProjects.builder().otherId(node.get("id").asText()).build();
                project.setTenantId(model.getTenantId());
                project.setSyncTime(model.getSendTime());
                project.setExtend(node);

                Optional<Long> id = this.databaseClient.execute("select id from timedoctor_projects " +
                        "where tenant_id =:tenantId and other_id =:otherId")
                        .as(Long.class)
                        .bind("tenantId", project.getTenantId())
                        .bind("otherId", project.getOtherId())
                        .fetch().one().blockOptional(Duration.ofSeconds(10));

                if (id.isPresent() && id.get() > 0) {
                    project.setId(id.get());
                    this.databaseClient.update().table(TimeDoctorProjects.class).using(project).fetch().rowsUpdated().block();
                } else {
                    this.databaseClient.insert().into(TimeDoctorProjects.class).using(project).fetch().rowsUpdated().block();
                }
            }
        }
    }
}
